package com.mediastory.spsserver.urgencyNotice.service.impl;

import java.io.File;
import java.net.URLEncoder;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.mediastory.spsserver.urgencyNotice.dao.UrgencyNoticeDao;
import com.mediastory.spsserver.urgencyNotice.domain.UrgencyNotice;
import com.mediastory.spsserver.urgencyNotice.service.UrgencyNoticeSvc;
import com.mediastory.spsserver.urgencyNoticeFile.dao.UrgencyNoticeFileDao;
import com.mediastory.spsserver.urgencyNoticeFile.domain.UrgencyNoticeFile;
import com.Ostermiller.util.Base64;

@Service
@Transactional
public class UrgencyNoticeSvcImpl implements  UrgencyNoticeSvc {

	@Autowired
	private MessageSourceAccessor messages;
	
	@Autowired
	UrgencyNoticeDao urgencyNoticeDao;
	
	@Autowired
	UrgencyNoticeFileDao urgencyNoticeFileDao;
	
	public UrgencyNoticeSvcImpl() {
		// TODO Auto-generated constructor stub
	}

	@Override
	public List<UrgencyNotice> findbyList(Map<String, Object> condition)
			throws Exception {
		// TODO Auto-generated method stub
		return (List<UrgencyNotice>) (urgencyNoticeDao.SelectList(condition));
	}

	public Map<String, Object> findbyListPaging(Map<String, Object> condition)
			throws Exception {
		// TODO Auto-generated method stub
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("urgencyNoticeList", (List<UrgencyNotice>) (urgencyNoticeDao.SelectList(condition)));
		resultMap.put("urgencyNoticeListTotalCnt", (Integer) (urgencyNoticeDao.SelectListTotalCnt(condition)));
		
		return resultMap;
	}

	@Override
	public UrgencyNotice findby(Map<String, Object> condition) throws Exception {
		// TODO Auto-generated method stub
		return urgencyNoticeDao.select(condition);
	}

	@Override
	public UrgencyNotice add(UrgencyNotice urgencyNotice) throws Exception {
		// TODO Auto-generated method stub
		UrgencyNotice result = null;
		List<File> fileList = new Vector<File>();
		
		try {
			// 노출이 Yes일 경우 기존 공지는 모두 노출 No로 수정
			if(urgencyNotice.getIsMain().equals("1")) {
				urgencyNoticeDao.updateAll(urgencyNotice);
			}
			result = urgencyNoticeDao.insert(urgencyNotice);
			
			//파일 업로드
			MultipartFile mFile = null;
			String fileType = "";
			String fileData = "";
			long fileSize = 0;
			if(urgencyNotice.getUrgencyNoticeFiles() != null){
				UrgencyNoticeFile urgencyNoticeFile = new UrgencyNoticeFile();
				
				for(int i = 0;i<urgencyNotice.getUrgencyNoticeFiles().size();i++){
					mFile = urgencyNotice.getUrgencyNoticeFiles().get(i);

					//파일의 크기가 0인 경우 넘긴다.
					if(mFile == null || mFile.getSize() == 0){
						continue;
					}
					
					fileType = urgencyNotice.getUrgencyNoticeFileTypes()[i];
					fileData = urgencyNotice.getUrgencyNoticeFileDatas()[i];
					fileData = fileData + "" + i;
					fileSize = mFile.getSize();
					
					long time = Calendar.getInstance().getTimeInMillis();
					String prefixNm = Base64.encode((URLEncoder.encode(urgencyNotice.getName(), "utf-8")+Long.toString(time)));
					//업로드 경로
					String uploadDir = messages.getMessage("file.urgencyNotice.uploadDir");
					//viewUrl
					String viewUrl = messages.getMessage("file.urgencyNotice.viewUrl");
					String fileNm = "";
					String url = "";
					
					if(fileType.equals("urgencyNoticeImg")){
						if(mFile != null && ! mFile.isEmpty() && mFile.getContentType().contains("image")){
							fileNm = prefixNm + "_urgencyNoticeImg."+(mFile.getOriginalFilename()).split("\\.")[1];
						}
					}else if(fileType.equals("urgencyNoticeImg2")){
						if(mFile != null && ! mFile.isEmpty() && mFile.getContentType().contains("image")){
							fileNm = prefixNm + "_urgencyNoticeImg2."+(mFile.getOriginalFilename()).split("\\.")[1];
						}
					}else if(fileType.equals("urgencyNoticeImg3")){
						if(mFile != null && ! mFile.isEmpty() && mFile.getContentType().contains("image")){
							fileNm = prefixNm + "_urgencyNoticeImg3."+(mFile.getOriginalFilename()).split("\\.")[1];
						}
					}else if(fileType.equals("urgencyNoticeImg4")){
						if(mFile != null && ! mFile.isEmpty() && mFile.getContentType().contains("image")){
							fileNm = prefixNm + "_urgencyNoticeImg4."+(mFile.getOriginalFilename()).split("\\.")[1];
						}
					}else{
						continue;
					}
					
					File file = new File(uploadDir+fileNm);
					url = viewUrl+fileNm;
					
					if(! file.isDirectory()){	//해당 폴더가 없을 경우 폴더 생성
						new File(uploadDir).mkdirs();
					}
					mFile.transferTo(file);
					
					fileList.add(file);
					
					//콘텐츠 파일 등록
					urgencyNoticeFile.setUrgencyNoticeIdx(result.getIdx());
					urgencyNoticeFile.setCreatedId(result.getCreatedId());
					urgencyNoticeFile.setCreatedIp(result.getCreatedIp());
					urgencyNoticeFile.setFileUrl(url);
					urgencyNoticeFile.setFileSize(fileSize);
					urgencyNoticeFile.setFileType(fileType);
					urgencyNoticeFile.setFileData(fileData);
					urgencyNoticeFileDao.insert(urgencyNoticeFile);
				}
			}

		} catch (Exception e) {
			// TODO: handle exception
			
			//업로드 파일 삭제
			for (File file : fileList) {
				file.delete();
			}
			
			throw e;
		}

		return result;
	}

	@Override
	public UrgencyNotice modify(UrgencyNotice urgencyNotice) throws Exception {
		// TODO Auto-generated method stub
		List<File> fileList = new Vector<File>();
		
		try {
			Map<String, Object> condition = new HashMap<String, Object>();
			condition.put("urgencyNoticeIdx", urgencyNotice.getIdx());

			//파일 업로드
			condition.put("modifiedId", urgencyNotice.getModifiedId());
			condition.put("modifiedIp", urgencyNotice.getModifiedIp());
			
			MultipartFile mFile = null;
			String fileType = "";
			String fileData = "";
			long fileSize = 0;

			if(urgencyNotice.getUrgencyNoticeFiles() != null){
				UrgencyNoticeFile urgencyNoticeFile = new UrgencyNoticeFile();
				
				for(int i = 0;i<urgencyNotice.getUrgencyNoticeFiles().size();i++){
					mFile = urgencyNotice.getUrgencyNoticeFiles().get(i);

					//파일의 크기가 0인 경우 넘긴다.
	 				if(mFile == null || mFile.getSize() == 0){
						continue;
					}
					
					fileType = urgencyNotice.getUrgencyNoticeFileTypes()[i];
					fileData = urgencyNotice.getUrgencyNoticeFileDatas()[i];
					fileData = fileData + "" + i;
					fileSize = mFile.getSize();
					
					long time = Calendar.getInstance().getTimeInMillis();
					String prefixNm = Base64.encode((URLEncoder.encode(urgencyNotice.getName(), "utf-8")+Long.toString(time)));
					//업로드 경로
					String uploadDir = messages.getMessage("file.urgencyNotice.uploadDir");
					//viewUrl
					String viewUrl = messages.getMessage("file.urgencyNotice.viewUrl");
					String fileNm = "";
					String url = "";
					
					if(fileType.equals("urgencyNoticeImg")){
						if(mFile != null && ! mFile.isEmpty() && mFile.getContentType().contains("image")){
							fileNm = prefixNm + "_urgencyNoticeImg."+(mFile.getOriginalFilename()).split("\\.")[1];
							//기존 등록된 파일 데이터 삭제
							condition.put("fileType", "urgencyNoticeImg");
							urgencyNoticeFileDao.delete(condition);
						}
					}else if(fileType.equals("urgencyNoticeImg2")){
						if(mFile != null && ! mFile.isEmpty() && mFile.getContentType().contains("image")){
							fileNm = prefixNm + "_urgencyNoticeImg2."+(mFile.getOriginalFilename()).split("\\.")[1];
							
							condition.put("fileType", "urgencyNoticeImg2");
							urgencyNoticeFileDao.delete(condition);
						}
					}else if(fileType.equals("urgencyNoticeImg3")){
						if(mFile != null && ! mFile.isEmpty() && mFile.getContentType().contains("image")){
							fileNm = prefixNm + "_urgencyNoticeImg3."+(mFile.getOriginalFilename()).split("\\.")[1];
							
							condition.put("fileType", "urgencyNoticeImg3");
							urgencyNoticeFileDao.delete(condition);
						}
					}else if(fileType.equals("urgencyNoticeImg4")){
						if(mFile != null && ! mFile.isEmpty() && mFile.getContentType().contains("image")){
							fileNm = prefixNm + "_urgencyNoticeImg4."+(mFile.getOriginalFilename()).split("\\.")[1];
							
							condition.put("fileType", "urgencyNoticeImg4");
							urgencyNoticeFileDao.delete(condition);
						}
					}else{
						continue;
					}				
			

					File file = new File(uploadDir+fileNm);
					url = viewUrl+fileNm;
					
					if(! file.isDirectory()){	//해당 폴더가 없을 경우 폴더 생성
						new File(uploadDir).mkdirs();
					}
					mFile.transferTo(file);
					
					fileList.add(file);
					
					//파일 등록
					urgencyNoticeFile.setUrgencyNoticeIdx(urgencyNotice.getIdx());
					urgencyNoticeFile.setCreatedId(urgencyNotice.getModifiedId());
					urgencyNoticeFile.setCreatedIp(urgencyNotice.getModifiedIp());
					urgencyNoticeFile.setFileUrl(url);
					urgencyNoticeFile.setFileSize(fileSize);
					urgencyNoticeFile.setFileType(fileType);
					urgencyNoticeFile.setFileData(fileData);
					urgencyNoticeFileDao.insert(urgencyNoticeFile);
				}
			}
			
			// 노출이 Yes일 경우 기존 공지는 모두 노출 No로 수정
			if(urgencyNotice.getIsMain().equals("1")) {
				urgencyNoticeDao.updateAll(urgencyNotice);
			}
						
			urgencyNotice = urgencyNoticeDao.update(urgencyNotice);
		} catch (Exception e) {
			// TODO: handle exception
			
			//업로드 파일 삭제
			for (File file : fileList) {
				file.delete();
			}
			
			throw e;
		}

		return urgencyNotice;
	}

	@Override
	public int remove(Map<String, Object> condition) throws Exception {
		// TODO Auto-generated method stub
		return urgencyNoticeDao.delete(condition);
	}

	@Override
	public Integer findbyChkNm(Map<String, Object> condition) throws Exception {
		// TODO Auto-generated method stub
		return urgencyNoticeDao.SelectListTotalCnt(condition);
	}

}